// lives/room/found.js
let comment_timer = null
let live_residue_duration_m_timer = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputFocus: true,
    comment: '',
    commentBottomHeight: 0,
    autopush: true,
    beauty: 5,
    whiteness: 5,
    device_position: "front",
    remote_mirror: false,
    enable_mic: true,
    enable_agc: false,
    enable_ans: false,
    push_url: '',
    type: false,
    statusBarHeight: 20,
    select_cat: !1,
    chek_address: !1,
    cameraContext:{},
    showSet: !1,
    mode: 'RTC',
    showGoods: !1,
    keyword: '',
    goods_id: [],
    camera: !1,
    goods_num: 0,
    comments: [], // 评论列表
    live: null,
    qingxidu: !1,
    showMeihua: !1,
    meihua_type:0,
    meiyan_type:0,
    room_title: '',
    is_pre_play: false,
    current_date: '',
    pre_play_date: '',
    pre_play_time: '',
    tips: '', // 平台提醒
    is_create: false, // 是否已经创建直播间
    is_stop: false, // 选择商品是否停止上拉加载
    page: 1, // 商品列表分页
    share_qrcode_active: false,
    share_qrcode: '',
  },

  onClickShare: function () {
    this.setData({
      share_qrcode_active: 'active'
    });
    getApp().request({
      url: getApp().api.live.qrcode,
      data: {
        room_id: this.data.room_id
      },
      success: res => {
        if (res.code == 0) {
          this.setData({
            share_qrcode: res.data.pic_url
          })
        } else {
          this.setData({
            share_qrcode_active: ''
          })
          wx.showToast({
            title: '生成海报失败',
            icon: 'error',
            duration: 2000
          })
        }
      },
      complete: () => {}
    })
  },

  onShareQrcodeClose: function () {
    this.setData({
      share_qrcode_active: ''
    })
  },

  saveGoodsQrcode: function () {
    if (this.data.share_qrcode == '') {
      return
    }
    var e = this;
    getApp().core.saveImageToPhotosAlbum ? (getApp().core.showLoading({
      title: "正在保存图片",
      mask: !1
    }), getApp().core.downloadFile({
      url: e.data.share_qrcode,
      success: function (o) {
        getApp().core.showLoading({
          title: "正在保存图片",
          mask: !1
        }), getApp().core.saveImageToPhotosAlbum({
          filePath: o.tempFilePath,
          success: function () {
            getApp().core.showModal({
              title: "提示",
              content: "直播间海报保存成功",
              showCancel: !1
            });
          },
          fail: function (o) {
            getApp().core.showModal({
              title: "图片保存失败",
              content: o.errMsg,
              showCancel: !1
            });
          },
          complete: function (o) {
            getApp().core.hideLoading();
          }
        });
      },
      fail: function (o) {
        getApp().core.showModal({
          title: "图片下载失败",
          content: o.errMsg + ";" + e.data.share_qrcode,
          showCancel: !1
        });
      },
      complete: function (o) {
        getApp().core.hideLoading();
      }
    })) : getApp().core.showModal({
      title: "提示",
      content: "当前版本过低，无法使用该功能，请升级到最新版本后重试。",
      showCancel: !1
    });
  },

  shareQrcodeClick: function(o) {
    var e = o.currentTarget.dataset.src;
    getApp().core.previewImage({
        urls: [ e ]
    });
  },
  /**
   * 点击评论
   */
  onClickComment: function () {
    this.setData({
      inputFocus: false
    })
  },

  /**
   * 监听input输入
   */
  onCommentInput: function (e) {
    this.setData({
      comment: e.detail.value
    })
  },

  /**
   * 评论发送
   */
  onCommentConfirm: function (e) {
    if (this.data.comment.trim != '') {
      wx.showLoading({
        title: '发送中...',
      });
      getApp().request({
        url: getApp().api.live.add_comment,
        data: {
          content: this.data.comment.trim(),
          room_id: this.data.room_id
        },
        method: 'POST',
        success: res => {
          if (res.code == 0) {
            wx.showToast({
              title: '评论成功',
              icon: 'none',
            })
            this.getComment()
          } else {
            wx.showToast({
              title: '评论失败',
              icon: 'none',
            })
          }
        },
        complete: () => {
          wx.hideLoading();
        }
      })
    }
    this.setData({
      comment: '',
      commentBottomHeight: 0,
      inputFocus: true
    })
  },

  /**
   * 评论框获取键盘高度
   */
  onCommentFocus: function (e) {
    this.setData({
      commentBottomHeight: e.detail.height
    })
  },

  /**
   * 评论框失去焦点
   */
  onCommentBlur: function () {
    this.setData({
      commentBottomHeight: 0,
      inputFocus: true
    })
  },

  // 监听状态变化
  onStateChange: function (e) {
    
  },

  liveStatus: function (type) {
    if (!this.data.room_id) {
      return
    }
    getApp().request({
      url: getApp().api.live.live_status,
      data:{
        room_id: this.data.room_id,
        type: type
      },
      method: 'POST',
      success: function() {
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var t = this;
    wx.getSystemInfo({
      success(res) {
        t.setData({
          statusBarHeight:res.statusBarHeight
        })
      }
    })
    getApp().page.onLoad(this, e);
    this.getInfo();
    this.cameraCon();
    this.initDateTime();
  },

  initDateTime: function () {
    var currentDate = new Date();
    var nowMonth = currentDate.getMonth() + 1;
    var strDate = currentDate.getDate();
    var seperator = '-';
    if (nowMonth >= 1 && nowMonth <= 9) {
      nowMonth = "0" + nowMonth;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var hour= currentDate.getHours();
    var minute = currentDate.getMinutes();
    this.setData({
      pre_play_date: currentDate.getFullYear() + seperator + nowMonth + seperator + strDate,
      current_date: currentDate.getFullYear() + seperator + nowMonth + seperator + strDate,
      current_time: hour + ':' + minute
    });
  },
  onDateChange: function (e) {
    this.setData({
      pre_play_date: e.detail.value
    })
  },
  onTimeChange: function (e) {
    this.setData({
      pre_play_time: e.detail.value
    })
  },
  /**
   * 预播状态
   */
  prePlayStatus: function () {
    this.setData({
      is_pre_play: !this.data.is_pre_play
    });
  },
  cameraCon: function () {
    this.setData({
      cameraContext: wx.createLivePusherContext("camera-push")
    });
    this.data.cameraContext.startPreview();
  },
  onLiveError: function (e) {
    console.log('直播错误')
    console.log(e)
  },
  /**
   * 获取申请内容
   */
  getInfo: function () {
    getApp().core.showLoading({
      title: "加载中"
    })
    var that = this;
    getApp().request({
      url: getApp().api.live.get_info,
      success: function (t) {
        if (t.code == 0) {
          that.setData({
            tips: t.data.tips
          })
          if (t.data.live_info) {
            
            if (t.data.live_info.mch_id && t.data.live_info.live_residue_duration_m == 0) {
              wx.showModal({
                title: '你还没有购买直播套餐时长，请先购买后使用哦',
                confirmText: "知道了",
                showCancel: false,
                success: function (res) {
                  if (res.confirm) {
                    //点击确定按钮
                    wx.navigateBack({
                      delta: 1,  // 返回上一级页面。
                      success: function() {
                          console.log('成功！')
                      }
                    })
                  } else if (res.cancel) {
                    //点击取消按钮
                  }
                }
              })
      
            }

            t.data.live_cat.forEach(function (item) {
              if (item.id == t.data.live_info.cat_id) {
                that.setData({
                  cat_name: item.name,
                  cat_id: item.id
                })
              }
            });
          } else {
            that.setData({
              cat_name: t.data.live_cat[0].name,
              cat_id: t.data.live_cat[0].id
            })
          }
          that.setData(t.data)
          if (that.data.room_type == 'pre') {
            that.setData({
              is_create: true,
              live_pic: that.data.room_info.pic_url,
              goods_id: that.data.room_info.goods_id,
              pre_play_date: that.data.room_info.pre_play_date,
              pre_play_time: that.data.room_info.pre_play_time,
              room_title: that.data.room_info.desc,
              room_id: that.data.room_info.id
            })
            if (that.data.room_info.address) {
              that.setData({
                chek_address: true,
                address: that.data.room_info.address
              })
            }
          }
          if (that.data.room_type == 'liveing') {
            that.setData({
              goods_id: that.data.room_info.goods_id,
              look_num: that.data.room_info.look_num,
              live_pic: that.data.room_info.pic_url,
              push_url: that.data.room_info.push_url,
              room_id: that.data.room_info.id,
              type: true,
              autopush: "true",
            })
            that.liveStatus('show')
            that.data.cameraContext.start();
            comment_timer = setInterval(() => {
              that.getComment()
            }, 5000)
          }
        }
      },
      complete: function (t) {
        getApp().core.hideLoading();
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    getApp().page.onShow(this);
    if (this.data.type) {
      this.liveStatus('show')
    }
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if (this.data.type) {
      this.liveStatus('hide')
    }
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (live_residue_duration_m_timer) {
      clearTimeout(live_residue_duration_m_timer)
    }
    if (comment_timer) {
      clearInterval(comment_timer)
    }
    if (this.data.type) {
      this.liveStatus('hide')
    }
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  get_address: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          address: res.name
        })
      }
    })
  },
  submitLive: function () {
    if (this.data.is_pre_play) {
      if (!this.data.pre_play_time) {
        wx.showModal({
          title: '提示',
          content: '请选择直播时间',
          showCancel: false
        });
        return false;
      }
      var currentDate = new Date();
      var pre_play_date = this.data.pre_play_date.replace(/-/g, '/');
      var selectDate = new Date(pre_play_date + ' ' + this.data.pre_play_time + ':00');
      if (currentDate.getTime() > selectDate.getTime()) {
        wx.showModal({
          title: '提示',
          content: '您选择的预播时间已到，是否直接开始直播？',
          success: (e) => {
            if (e.confirm) {
              this.setData({
                is_pre_play: false
              });
              this.start_live();
            }
          }
        });
        return false;
      }
    }
    this.start_live();
  },
  // 开始直播，预播
  startPlay: function () {
    console.log('预播开始直播啦')
    if (this.data.room_title == '') {
      wx.showModal({
        title: '提示',
        content: '请填写直播间标题',
        showCancel: false
      });
      return false;
    }
    getApp().core.showLoading({
      title: "提交中"
    })
    getApp().request({
      url: getApp().api.live.start_live_by_pre,
      data: {
        room_id: this.data.room_info.id,
        address: this.data.address ? this.data.address : '',
        chek_address: this.data.chek_address ? this.data.chek_address : 0,
        live_pic: this.data.live_pic ? this.data.live_pic : '',
        goods_id: '['+this.data.goods_id.toString()+']',
        room_title: this.data.room_title
      },
      method: "post",
      success: res => {
        if (res.code == 0) {
          this.setData({
            push_url: res.data.room_info.push_url,
            autopush: "true",
            type: true,
            room_id: res.data.room_info.id,
            is_create: false
          })
          this.data.cameraContext.start();
          comment_timer = setInterval(() => {
            this.getComment()
          }, 5000)

          live_residue_duration_m_timer =  setTimeout(function() {
            this.live_residue_duration_over();
         }, this.live_info.live_residue_duration_m);
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false
          });
        }
      },
      complete: () => {
        getApp().core.hideLoading()
      }
    })
  },
  start_live: function () {
    var that = this;
    if (!that.data.live_pic) {
      wx.showModal({
        title: '提示',
        content: '请上传封面',
        showCancel: false
      });
      return false;
    }
    if (this.data.room_title == '') {
      wx.showModal({
        title: '提示',
        content: '请填写直播间标题',
        showCancel: false
      });
      return false;
    }
    getApp().core.showLoading({
      title: "提交中"
    })
    getApp().request({
      url: getApp().api.live.push,
      data:{
        address: that.data.address ? that.data.address : '',
        cat_id: that.data.cat_id,
        chek_address: that.data.chek_address ? that.data.chek_address : 0,
        live_pic: that.data.live_pic ? that.data.live_pic : '',
        goods_id: '['+that.data.goods_id.toString()+']',
        room_title: that.data.room_title,
        is_pre_play: that.data.is_pre_play,
        pre_play_date: that.data.pre_play_date,
        pre_play_time: that.data.pre_play_time
      },
      method: "post",
      success: function (t) {
        if (t.code == 0) {
          if (that.data.is_pre_play) {
            that.setData({
              is_create: true,
              room_id: t.data.room_id,
              room_info: t.data.room_info
            })
          } else {
            if (t.data.push_url) {
              that.setData({
                push_url:t.data.push_url,
                autopush: "true",
                type: !0,
                room_id: t.data.room_id
              })

              that.data.cameraContext.start();
              comment_timer = setInterval(() => {
                that.getComment()
              }, 5000)
              live_residue_duration_m_timer =  setTimeout(function() {
                 this.live_residue_duration_over();
              }, this.live_info.live_residue_duration_m);
            } else {
              wx.showModal({
                title: '提示',
                content: '获取推流地址失败，请重新开启',
                showCancel: false
              });
            }
          }
        } else {
          wx.showModal({
            title: '提示',
            content: t.msg,
            showCancel: false
          });
        }
      },
      complete: function (t) {
        getApp().core.hideLoading();
      }
    })
  },
  live_residue_duration_over: function () {
    var that = this;
    wx.showModal({
      title: "提示",
      content: '非常抱歉，您购买的直播时长已使用完，暂时无法直播',
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          that.end_lives();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  end_live: function () {
    var that = this;
    wx.showModal({
      title: "提示",
      content: '确认结束直播吗',
      showCancel: true,
      success: function (res) {
        if (res.confirm) {
          that.end_lives();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  end_lives: function () {
    getApp().core.showLoading({
      title: "关闭中"
    })
    var that = this;
    getApp().request({
      url: getApp().api.live.end,
      success: function (t) {
        if (t.code == 0) {
          that.setData({
            type: !1
          })
          that.data.cameraContext.stop();
          wx.redirectTo({
            url: '/lives/room/end'
          })
        } else {
          wx.showModal({
            title: '提示',
            content: t.msg,
            showCancel: false
          });
        }
      },
      complete: function (t) {
        getApp().core.hideLoading();
      }
    })
  },
  bindChange: function (e) {
    const val = e.detail.value
    console.log(val[0]);
    var cat_name = this.data.live_cat[val[0]].name
    var cat_id = this.data.live_cat[val[0]].id
    this.setData({
      cat_name: cat_name,
      cat_id: cat_id
    })
  },
  select_cat_f: function () {
    var that = this;
    that.setData({
      select_cat: !that.data.select_cat
    })
  },
  address_status: function () {
    var that = this;
    that.setData({
      chek_address: !that.data.chek_address
    })
  },
  backOne:function () {
    wx.navigateBack({
      delta: 1 
    })
  },
  chooseImage: function () {
    var that = this
    wx.chooseImage({
      sourceType: ['album', 'camera'],
      count: 1,
      success: function (res) {
        that.updloadImg(res.tempFilePaths)
      }
    })
  },
  updloadImg: function (imageList) {
    wx.showLoading({
      title: '上传中',
    })
    var that = this;
    wx.uploadFile({
      url: getApp().api.default.upload_image,
      filePath: imageList[0],
      name: 'image',
      success: function (res) {
        var data_obj = JSON.parse(res.data);
        if (data_obj.code == 0) {
          var pic_img = data_obj.data.url;
          that.setData({
            live_pic:pic_img
          })
        }else {
          wx.showModal({
            title: '提示',
            content: res.msg
          })
        }

      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  fanzhuan: function () {
    this.data.cameraContext.switchCamera({
      success: function(res) {
        console.log(res);
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    })
    // console.log(LivePusherContext);
    // var that = this;
    // that.setData({
    //   device_position: that.data.device_position == 'front' ? 'back' : 'front'
    // })
  },
  showSetting: function () {
    var that = this;
    that.setData({
      showSet: !that.data.showSet
    })
  },
  set_mode: function (t) {
    var type = t.currentTarget.dataset.type;
    this.setData({
      mode: type
    })
  },
  beautyChange: function (t) {
    this.setData({
      beauty: t.detail.value
    });
  },
  whitenessChange: function (t) {
    this.setData({
      whiteness: t.detail.value
    });
  },
  switchMIC: function (t) {
    console.log(t)
    if (t.detail.value) {
      this.setData({
        enable_mic: true
      })
      this.data.cameraContext.setMICVolume({
        volume:1.0
      })
    }else {
      this.setData({
        enable_mic: false
      })
      this.data.cameraContext.setMICVolume({
        volume: 0.0
      })
    }
  },
  switchenableans: function (t) {
    if (t.detail.value) {
      this.setData({
        enable_ans: true
      })
    } else {
      this.setData({
        enable_ans: false
      })
    }
  },
  // 搜索商品，暂时无用
  // inputConfirm: function (t) {
  //   var a = this, e = t.detail.value;
  //   0 != e.length && (a.setData({
  //     keyword: e
  //   }), a.getGoods());
  // },
  getGoods: function () {
    this.setData({
      showGoods: 1,
      // is_live: !1
    })
    wx.showLoading({
      title: '加载中',
    })
    var e = this;
    getApp().request({
      url: getApp().api.live.get_goods_list,
      data: {
        anchor_id: e.data.live_info.id,
        type: 'live',
        keyword: ''
      },
      success: data => {
        if (data.code == 0) {
          var goods_list = data.data.list
          goods_list.forEach(item => {
            if (this.data.goods_id.indexOf(item.goods_id) > -1) {
              item.is_add_live = 1
            } else {
              item.is_add_live = 0
            }
          })
          e.setData({
            goods_list: goods_list
          })
        }
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },
  hiddenGoods: function () {
    this.setData({
      showGoods: !1,
      page: 1,
      is_stop: false
    })
  },
  addGoods: function (t) {
    var id = t.currentTarget.dataset.id;
    var index = t.currentTarget.dataset.index;
    var goods_id = this.data.goods_id;
    goods_id.push(id)
    var goods_list = this.data.goods_list;
    goods_list[index].is_add_live = 1;
    this.setData({
      goods_id: goods_id,
      goods_list: goods_list
    })
  },
  delGoods: function (t) {
    var id = t.currentTarget.dataset.id;
    var index = t.currentTarget.dataset.index;
    var goods_id = this.data.goods_id;
    var goods_list = this.data.goods_list;
    goods_list[index].is_add_live = 0;
    var i = goods_id.indexOf(id);
    if (i > -1) {
      goods_id.splice(i, 1);
    }
    this.setData({
      goods_id: goods_id,
      goods_list: goods_list
    })
  },
  switchCamera: function () {
    var that = this;
    this.data.cameraContext.switchCamera()
    this.setData({
      camera: !that.data.camera
    })
  },
  getGoodsInfo: function () {
    this.setData({
      showGoods: 1,
      is_live: 1,
      goods_list: []
    })
    wx.showLoading({
      title: '加载中',
    })
    var e = this;
    getApp().request({
      url: getApp().api.live.get_goods,
      data: {
        room_id: e.data.room_id
      },
      success: function (t) {
        if (0 == t.code) {
          e.setData({
            goods_list: t.data.list,
          });
        }else {
          wx.showModal({
            title: '提示',
            content: t.msg
          })
        }
      },
      complete: function () {
        wx.hideLoading()
      }
    });
  },
  /**
   * 获取评论last_id
   */
  getCommentLastId: function () {
    if (this.data.comments.length > 0) {
      return this.data.comments[this.data.comments.length - 1].id
    }
    return 0
  },

  /**
   * 获取评论内容及点赞数量
   */
  getComment: function () {
    var that = this;
    // let cache_like = wx.getStorageSync('live_room_like_' + this.data.room_id)
    getApp().request({
      url: getApp().api.live.get_comment,
      data: {
        last_id: this.getCommentLastId(),
        // like_count: cache_like ? cache_like : 0,
        like_count: 0,
        room_id: this.data.room_id
      },
      success: res => {
        if (res.code == 0) {
          let live = that.data.live
          that.setData({
            look_num: res.data.look_num ? res.data.look_num : 0,
            comments: that.data.comments.concat(res.data.list)
          })
          if (res.data.list.length > 0) {
            that.setData({
              scrollIntoView: 'comment-id-' + that.data.comments.length
            })
          }

          // wx.setStorageSync('live_room_like_' + that.data.room_id, 0)
        }
      },
      complete: () => {
        wx.hideLoading();
      }
    })
  },
  hidden_meihua: function () {
    var that = this;
    that.setData({
      showMeihua: !that.data.showMeihua
    })
  },
  hidden_setting: function () {
    var that = this;
    that.setData({
      qingxidu: !1,
      live_setting: !1
    })
  },
  show_qingxidu: function () {
    this.setData({
      qingxidu: 1
    })
  },
  show_live_setting: function () {
    this.setData({
      live_setting: 1
    })
  },
  // 切换美颜
  onchengMeiyan:function (t) {
    var type = t.currentTarget.dataset.type;
    this.setData({
      meiyan_type:type
    })
  },
  update_text: function (t) {
    this.setData({
      room_title: t.detail.value
    })
  },
  // 商品列表上拉加载
  onGoodsScroll: function () {
    if (this.data.is_stop || this.data.is_live) {
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    getApp().request({
      url: getApp().api.live.get_goods_list,
      data: {
        anchor_id: this.data.live_info.id,
        type: 'live',
        keyword: '',
        page: this.data.page + 1
      },
      success: data => {
        if (data.code == 0) {
          if (data.data.list.length > 0) {
            var goods_list = data.data.list
            goods_list.forEach(item => {
              if (this.data.goods_id.indexOf(item.goods_id) > -1) {
                item.is_add_live = 1
              } else {
                item.is_add_live = 0
              }
            })
            this.setData({
              goods_list: this.data.goods_list.concat(goods_list),
              page: this.data.page + 1
            })
          } else {
            this.setData({
              is_stop: true
            });
          }
        }
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  }
})
